package protoctl

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"time"

	"gitee.com/lcc_dr/restful-api-demo/apps"
	"gitee.com/lcc_dr/restful-api-demo/conf"
	"github.com/gin-gonic/gin"
	"github.com/infraboard/mcube/logger"
	"github.com/infraboard/mcube/logger/zap"
)

type HttpServer struct {
	srv *http.Server
	log logger.Logger
	g   gin.IRouter
}

func (h *HttpServer) Start() error {

	// g := gin.Default()
	// apps.InitGin(g)
	h.log.Infof("start GinHttpServer listenAndServe is %s", h.srv.Addr)
	if err := h.srv.ListenAndServe(); err != nil {

		if errors.Is(err, http.ErrServerClosed) {
			h.log.Info("stop GinHttpServer Success")

		} else {
			h.log.Errorf("Failed to listen and GinHttpServer,error: %v", err)

			return err

		}

	}
	return nil
}

func (h *HttpServer) Stop() error {

	h.log.Info("httpServer exiting")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	if err := h.srv.Shutdown(ctx); err != nil {
		h.log.Errorf("Server forced to shutdown:", err)
	}

	return nil

}

func NewHttpServer() *HttpServer {

	g := gin.Default()
	apps.InitGin(g)
	addr := fmt.Sprintf("%s:%s", conf.GetConf().App.Host, conf.GetConf().App.Port)
	srv := &http.Server{
		Addr:              addr,
		Handler:           g,
		ReadHeaderTimeout: 60 * time.Second,
		ReadTimeout:       60 * time.Second,
		WriteTimeout:      60 * time.Second,
		IdleTimeout:       60 * time.Second,
		MaxHeaderBytes:    1 << 20, // 1M

	}
	return &HttpServer{
		srv: srv,
		g:   g,
		log: zap.L().Named("gin-http-server"),
	}
}
